import Vue from 'vue'
import Config from '@/common/Config.js'


//新封装请求方法,暂不可用
function request(url, params, method, tokenType) {
	if(!tokenType){
		// 默认user用户
		tokenType = "user"
	}
	//========================= 处理token
	var token = null;
	if ('/api/user/login' != url && '/api/user/register' != url&&url!='/api/sms/send'&&url!='/api/user/resetpwd'&&url!='/order/generateConfirmOrderByCart') {
		var userInfo = uni.getStorageSync('userInfo');
		if (userInfo) {
			token = userInfo.token;
			params['token'] = token;
		}
	}
	//========================= 通用请求头部参数
	let header_data = {
		'content-type': "application/x-www-form-urlencoded",
		'Authorization': token
	}
	if(method == "POST_JSON"){
		// 如果是JSON提交，单独处理一下头部
		header_data["content-type"] = "application/json;charset=UTF-8";
		method = "POST";
		params = JSON.stringify(params);
	}
	
	
	//========================= 请求
	return new Promise((resolve, reject) =>{
		uni.request({
			url: Config.serverUrl + url,
			method: method,
			header: header_data,
			data: params,
			traditional: true,
			success: res => {
				if (res.statusCode == 401 || res.data.code == 401) {
					// 刷新token
					refreshToken(tokenType,()=>{
						// 再调用一次
						request(url, params, method, tokenType);
					});
					return;
				}
				resolve(res.data)
			},
			fail: (error) => {
				// console.log(error);
				reject(error)
				if (errosr.errMsg == "request:fail timeout") { //网络请求超时
					toast("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					toast("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					toast("请求失败");
				} else {
					toast("加载失败");
				}
			},
			complete: () => {}
		});
	})
}




function upload_datas(params, method, url1, success) {
	
	// 判断是否用前端Json文件中的测试数据
	// if (Config.unfold_data_environment == "test") {
	// 	return;
	// } else if (Config.unfold_data_environment == "dev") {
	// 	var userInfo = uni.getStorageSync("userInfo");
	// 	var token = "";
	// 	if ('/api/user/login' != url1 && '/api/user/register' != url1&&url1!='/api/sms/send'&&url1!='/api/user/resetpwd'&&url1!='/order/generateConfirmOrderByCart') {
	// 		if(userInfo){
	// 			token = userInfo.token;
	// 			params['token'] = token;
	// 		}else{
	// 			// showWindow("请先登录");
	// 			uni.reLaunch({
	// 				url: '/pages/login/login',
	// 			});
	// 			return;
	// 		}
	// 	}
	    if(Config.token){
	       params['token'] = Config.token;
	    }
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.oldUrl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});
	// }

}

function log_data(params, method, url1, success) {
	// 判断是否用前端Json文件中的测试数据
	// if (Config.unfold_data_environment == "test") {
	// 	return;
	// } else if (Config.unfold_data_environment == "dev") {
	// 	var userInfo = uni.getStorageSync("userInfo");
	// 	var token = "";
	// 	if ('/api/user/login' != url1 && '/api/user/register' != url1&&url1!='/api/sms/send'&&url1!='/api/user/resetpwd'&&url1!='/order/generateConfirmOrderByCart') {
	// 		if(userInfo){
	// 			token = userInfo.token;
	// 			params['token'] = token;
	// 		}else{
	// 			// showWindow("请先登录");
	// 			uni.reLaunch({
	// 				url: '/pages/login/login',
	// 			});
	// 			return;
	// 		}
	// 	}
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.logurl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});
	// }

}


function upload_data(params, method, url1, success) {
	// 判断是否用前端Json文件中的测试数据
        if(Config.token){
		   params['token'] = Config.token;
		}
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.dnsurl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});

}

function yh_data(params, method, url1, success) {
	// 判断是否用前端Json文件中的测试数据
        if(Config.token){
		   params['token'] = Config.token;
		}
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.yhUrl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});

}
function ewm_data(params, method, url1, success) {
	// 判断是否用前端Json文件中的测试数据
        if(Config.token){
		   params['token'] = Config.token;
		}
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.wUrl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});

}


//商家指定
function shop_ajax(params, method, url1, success) {
		
		if(Config.token){
		   params['token'] = Config.token;
		}
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.teaurl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});
	

}

//新版页面接口请求
function new_data(params, method, url1, success) {
	if(Config.token){
	   params['token'] = Config.token;
	}
	// 判断是否用前端Json文件中的测试数据
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.newurl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});

}



//商家入驻

function tea_data(params, method, url1, success) {
	if(Config.token){
	   params['token'] = Config.token;
	}
	// 判断是否用前端Json文件中的测试数据
		//判断该请求是否需要登录校验
		var contentType = "application/x-www-form-urlencoded";
		if(url1=='/api/common/imgAsBase64'){
			var contentType = "multipart/form-data";
		}
		// console.log("提交地址:" +url1);
		// console.log("提交参数:" + JSON.stringify(params));
		uni.request({
			url: Config.teaurl + url1,
			method: method,
			header: {
				'content-type': contentType,
				// 'token':token,
				// 'Access-Control-Allow-Origin':'*',
				// 'Access-Control-Allow-Headers':'Content-Type,Token',
				// 'Access-Control-Allow-Methods':'GET, POST, PUT, DELETE, OPTIONS',
				// 'Access-Control-Allow-Headers':'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild',
				// 'Access-Control-Allow-Origin':Config.dnsurl
			},
			data: params,
			traditional: true,
			success: success,
			fail: (error) => {
				if (error.errMsg == "request:fail timeout") { //网络请求超时
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail 请求超时。") {
					showWindow("网络不稳定，请检查网络设置");
				} else if (error.errMsg == "request:fail ") {
					showWindow("请求失败");
				} else {
					showWindow("加载失败");
				}
			},
			complete: () => {}
		});

}



function showWindow(txt) {
	uni.showToast({
		title: txt,
		icon: "none",
		duration: 2000
	})
}
// uni.showModal({
//     title: '提示',
//     content: '这是一个模态弹窗',
//     success: function (res) {
//         if (res.confirm) {
//             console.log('用户点击确定');
//         } else if (res.cancel) {
//             console.log('用户点击取消');
//         }
//     }
// });

// parseFloat(tixian_data.money_info.tixianzhong).toFixed(2)
// 时间格式转换2020-02-10
function getMyDate(str) {
	var oDate = new Date(str),
		oYear = oDate.getFullYear(),
		oMonth = oDate.getMonth() + 1,
		oDay = oDate.getDate(),
		oHour = oDate.getHours(),
		oMin = oDate.getMinutes(),
		oSen = oDate.getSeconds(),
		oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay); //最后拼接时间  
	// console.log("data:" + oDate);
	return oTime;
};
//年月日时分
function getYMD(str) {
	var oDate = new Date(str),
	
		oYear = oDate.getFullYear(),
		oMonth = oDate.getMonth() + 1,
		oDay = oDate.getDate(),
		oHour = oDate.getHours(),
		oMin = oDate.getMinutes(),
		
		oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin); //最后拼接时间  
	
	return oTime;
};
// 时间格式转换2020-02-10 12:12:12
function getMyDatetime(str) {
	var oDate = new Date(str),
	
		oYear = oDate.getFullYear(),
		oMonth = oDate.getMonth() + 1,
		oDay = oDate.getDate(),
		oHour = oDate.getHours(),
		oMin = oDate.getMinutes(),
		oSen = oDate.getSeconds(),
		oTime = oYear + '-' + getzf(oMonth) + '-' + getzf(oDay) + ' ' + getzf(oHour) + ':' + getzf(oMin) + ':' + getzf(oSen); //最后拼接时间  
	return oTime;
};
//补0操作
function getzf(num) {
	if (parseInt(num) < 10) {
		num = '0' + num;
	}
	return num;
};



function setzf(p){
	let u = uni.getStorageSync("userInfo");
	let d = u.user_id;
	let a =  new Date();
	a = a.getTime().toString().substr(0,8);
	let b = a+"Hln6rfMs"+p+d;
	let z = new zf.zf();
    let m = z.set(b);
	return m;
}

/**
 * 预览图片
 * imageList：图片集合
 * index：当前图片index
 */
function previewImage(imageList, index) {
	for (let i = 0; i < imageList.length; i++) {
		if (imageList[i].indexOf(Config.dnsurl) == -1) {
			let img = Config.dnsurl + "/" + imageList[i];
			imageList[i] = img;
		}
	}
	uni.previewImage({
		current: imageList[index],
		urls: imageList
	});
};
// 返回的是字符串，需要的时候注意改变类型
function getCurPageOption(){
	/*获取当前路由*/
	let pages = getCurrentPages();
	let curPage = pages[pages.length-1];
	// 在微信小程序或是app中，通过curPage.options；如果是H5，则需要curPage.$route.query（H5中的curPage.options为undefined，所以刚好就不需要条件编译了）
	let curParam = curPage.options || curPage.$route.query;
	return curParam;
}
// 下拉刷新
// onPullDownRefresh() {
// 	console.log('refresh');
// 	setTimeout(function() {
// 		uni.stopPullDownRefresh();
// 	}, 1000);
// },

// 第三方外部链接跳转
function externalLinks(url){
	    // #ifdef APP-PLUS
		plus.runtime.openURL(url);
	    // #endif
	    // #ifdef H5
	    window.location.href = url;
	    // #endif

}

//微信config
function wxconfig(s){
	jweixin.config({
		debug: false,
		appId: s.appId,
		timestamp: s.timestamp,
		nonceStr: s.noncestr,
		signature: s.sign,
		jsApiList: [
			'onMenuShareTimeline',
			'onMenuShareAppMessage',
			'chooseWXPay',
			'scanQRCode'
		]
	});
}

//微信支付
function Wmany_pay(type,pay_params,s,result_function){
	wxconfig(s)
	if(type == 3){
		jweixin.chooseWXPay({
			appId:pay_params.appId,
			provider: 'wxpay',
		   nonceStr: pay_params.nonceStr,
		   timestamp: pay_params.timeStamp,
		   package: pay_params.packageValue,
		   signType: pay_params.signType,
		   paySign: pay_params.paySign,
		   success: result_function,
		   fail: function(res) {
				showWindow(JSON.stringify(err));
				showWindow("支付失败");
		   },
		   complete: function(res) {
		   },
		})
	}
}
//微信支付   支付
function money_pay(type,pay_params,result_function){
// showWindow(JSON.stringify(pay_params))
	// return;
	let pay_info = pay_params
     
	 uni.requestPayment({
		   provider: 'wxpay',
			orderInfo: JSON.stringify(pay_info), //订单数据
			success:function(){
				result_function(this);
			},
			fail(err) {
				uni.hideLoading()
				showWindow("支付失败");
			}
	  });
	
}
//支付宝支付
function money_pays(type,pay_params,result_function){
// showWindow(JSON.stringify(pay_params))
	// return;
	let pay_info = pay_params

	 uni.requestPayment({
		   provider: 'alipay',
			orderInfo: JSON.stringify(pay_info), //订单数据
			success:function(){
				result_function(this);
			},
			fail(err) {
				console.log("支付宝支付失败",err);
				uni.hideLoading()
				showWindow("支付失败");
			}
	  });
	
}




function jsappWxPay(data,success_fuc){
	
	let msg = typeof(WeixinJSBridge);
	
	if(msg !== "undefined"){
		WeixinJSBridge.invoke(
		   'getBrandWCPayRequest', data,
		   function(res){
			   if(res.err_msg == "get_brand_wcpay_request:ok" ){
					  // 使用以上方式判断前端返回,微信团队郑重提示：//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
					  uni.showToast({
						icon:"none",
						title:"支付成功"
					  })
					  success_fuc();
			   }else if(res.err_msg !== "get_brand_wcpay_request:cancel"){
					uni.showToast({
						icon:"none",
						title:"支付失败，网络异常，请稍后再试"
					})
					let userInfo = uni.getStorageSync("userInfo");
					let data = {user_id:userInfo.user_id,msg:"微信jsAPI支付出现异常",content:res.err_msg};
					uni.request({
						url:"http://app.jialianxin.cn/api/error/index/add",
						data:data,
						method:"POST"
					})
			   }
		}); 
	}else{
		uni.showModal({
			  title:"提示",
			  content:"微信不支持，请换其他支付方式或下载APP进行支付"
		})
	}
	
}




function hasOwnProperty(d,k){
	let r = false;
	if(d==null){return r;}
	for(let kn in d){
		if(kn==k){
			r=true;
			break;
		}
	}
	return r;
}

function getUserQuanyi(name){
	let userInfo = uni.getStorageSync("userInfo");
	if(hasOwnProperty(userInfo.quanyi,name)){
	  return userInfo.quanyi[name]	
	}else{
	 return null;	
	}
}

function setUserQuanyi(v){
	let userInfo = uni.getStorageSync("userInfo");
	userInfo.quanyi=v;
	uni.setStorageSync("userInfo",userInfo);
}

/**
 * 刷新token
 */
function refreshToken(res){
	if(res.statusCode==401 && res.data.code==401){
		upload_data({}, 'POST', '/api/token/refresh', res => {
			if (res.statusCode == 200 && res.data.code == 1) {
				var userInfo = uni.getStorageSync("userInfo");
				userInfo.token = res.data.data.token;
				uni.setStorageSync('userInfo',userInfo)
			} else {
				showWindow(res.data.msg);
				setTimeout(function() {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1000);
			}
		});
	}
}
/**
 * app，小程序端扫码
 * */
 function scanCode(result_function){
	uni.scanCode({
	    scanType: ['barCode','qrCode'],
	    success:result_function,
	});
 }
 
export default {
	upload_data,
	upload_datas,
	new_data,
	tea_data,
	yh_data,
	showWindow,
	getMyDate,
	getMyDatetime,
	previewImage,
	getCurPageOption,
	money_pay,
	Wmany_pay,
	externalLinks,
	refreshToken,
	getYMD,
	scanCode,
	getUserQuanyi,
	setUserQuanyi,
	shop_ajax,
	money_pays,
	Config,
	log_data,
	ewm_data
}
